package com.cicdi.controller;

import com.cicdi.model.MyTallyResult;
import com.cicdi.util.Common;
import com.cicdi.util.Web3jUtil;
import com.platon.contracts.ppos.dto.resp.Proposal;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author haypo
 * @date 2021/3/9
 */
public class GovernmentController implements Initializable {
    @FXML
    public TableView<MyTallyResult> proposalTable;
    @FXML
    public TableColumn<Proposal, String> proposalTitle;
    @FXML
    public TableColumn<Proposal, String> proposalType;
    @FXML
    public TableColumn<Proposal, String> proposalStatus;
    @FXML
    public TableColumn<Proposal, String> endVotingBlock;
    @FXML
    public TableColumn<Proposal, String> submitBlock;

    public static List<MyTallyResult> getMyTallyResultList() {
        return Web3jUtil.getProposalList().stream().map(
                proposal -> {
                    try {
                        return new MyTallyResult(proposal);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
        ).collect(Collectors.toList());
    }

    /**
     * 设置治理面板
     */
    public void governmentTab() {
        proposalTitle.setCellValueFactory(new PropertyValueFactory<>("proposalId"));
        proposalType.setCellValueFactory(new PropertyValueFactory<>("proposalType"));
        proposalStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
        submitBlock.setCellValueFactory(new PropertyValueFactory<>("submitBlock"));
        endVotingBlock.setCellValueFactory(new PropertyValueFactory<>("endVotingBlock"));

        List<MyTallyResult> tallyResults = getMyTallyResultList();
        ObservableList<MyTallyResult> observableList = FXCollections.observableArrayList(tallyResults);
        observableList.sort((o1, o2) -> o2.getSubmitBlock().compareTo(o1.getSubmitBlock()));
        proposalTable.setItems(observableList);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Common.SCHEDULED_THREAD_POOL_EXECUTOR.scheduleWithFixedDelay(
                () -> Platform.runLater(this::governmentTab), 1, 10, TimeUnit.SECONDS);
    }
}
